﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoriPeter.FitnessJournal8.Models
{
    public static class MergeLists
    {
        public static List<T> Merge<T>(this List<T> _list1, List<T> _list2) where T : IIdentifiable, IMergeable<T>
        {
            Dictionary<int, T> dict1 = (Dictionary<int, T>)Activator.CreateInstance<Dictionary<int, T>>();
            foreach (var item in _list1)
            {
                dict1.Add(item.GetIdentifier(), item);
            }

            foreach (var item in _list2)
            {
                if (dict1.ContainsKey(item.GetIdentifier()))
                {
                    T element;
                    dict1.TryGetValue(item.GetIdentifier(), out element);
                    element.Merge(item);
                } else
                {
                    _list1.Add(item);
                }
            }

            return _list1;
        }

        public static List<T> Merge<T>(this List<T> _list, T _item) where T : IIdentifiable, IMergeable<T>
        {
            if (_list.Where(e => e.GetIdentifier() == _item.GetIdentifier()).Count() > 0)
            {
                var oldItem = _list.Where(e => e.GetIdentifier() == _item.GetIdentifier()).First();
                oldItem.Merge(_item);
            }
            else
            {
                _list.Add(_item);
            }

            return _list;
        }
    }
}
